<template>
  <div class="mobile-refund-task">
    <!-- 顶部导航栏 -->
    <div class="mobile-header">
      <div class="header-content">
        <h1 class="header-title">
          <i class="bi bi-list-task"></i>
          退款任务管理
        </h1>
        <div class="header-actions">
          <button 
            class="btn btn-sm btn-outline-light"
            @click="refreshData"
            :disabled="loading"
          >
            <i class="bi bi-arrow-clockwise"></i>
          </button>
          <button 
            class="btn btn-sm btn-outline-light"
            @click="logout"
          >
            <i class="bi bi-box-arrow-right"></i>
          </button>
        </div>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="mobile-content">
      <!-- 创建任务按钮 -->
      <div class="create-task-section">
        <button 
          class="btn btn-primary btn-lg w-100 create-task-btn"
          @click="createRefundTask"
          :disabled="loading || !canCreateNewTask"
        >
          <i class="bi bi-plus-circle"></i>
          <span v-if="loading">创建中...</span>
          <span v-else>创建退费任务</span>
        </button>
        
        <!-- 创建任务提示 -->
        <div v-if="!canCreateNewTask && masterData.length > 0" class="create-tip">
          <div class="alert alert-warning">
            <i class="bi bi-exclamation-triangle"></i>
            需要完成当前任务中所有患者的联系工作后，才能创建新的退费任务
          </div>
        </div>
      </div>

      <!-- 任务列表 -->
      <div class="task-list" v-if="masterData.length > 0">
        <div 
          v-for="item in masterData" 
          :key="item.id"
          class="task-card"
          @click="showDetails(item.id)"
        >
          <!-- 任务头部信息 -->
          <div class="task-header">
            <div class="task-id">
              <i class="bi bi-hash"></i>
              任务 {{ item.id }}
            </div>
            <div class="task-date">
              {{ formatDateTime(item.inputDate) }}
            </div>
          </div>

          <!-- 进度信息 -->
          <div class="task-progress">
            <div class="progress-info">
              <span class="progress-text">联系进度</span>
              <span class="progress-numbers">
                {{ item.contactedCount || 0 }} / {{ item.accountCount || 0 }}
              </span>
            </div>
            <div class="progress-bar-container">
              <div 
                class="progress-bar-fill"
                :class="getProgressBarClass(item.contactedCount, item.accountCount)"
                :style="{ width: getProgressPercentage(item.contactedCount, item.accountCount) + '%' }"
              ></div>
            </div>
            <div class="progress-percentage">
              {{ getProgressPercentage(item.contactedCount, item.accountCount) }}%
            </div>
          </div>

          <!-- 统计信息 -->
          <div class="task-stats">
            <div class="stat-item">
              <div class="stat-label">总金额</div>
              <div class="stat-value amount">{{ formatCurrency(item.accountSumBalance) }}</div>
            </div>
            <div class="stat-item">
              <div class="stat-label">总记录</div>
              <div class="stat-value">{{ item.accountCount }}</div>
            </div>
          </div>

          <!-- 备注 -->
          <div v-if="item.notes" class="task-notes">
            <i class="bi bi-sticky"></i>
            {{ item.notes }}
          </div>

          <!-- 操作指示 -->
          <div class="task-action">
            <i class="bi bi-chevron-right"></i>
          </div>
        </div>
      </div>

      <!-- 无数据提示 -->
      <div class="empty-state" v-if="masterData.length === 0 && !loading">
        <div class="empty-icon">
          <i class="bi bi-inbox"></i>
        </div>
        <div class="empty-title">暂无退费任务</div>
        <div class="empty-subtitle">点击上方按钮创建新的退费任务</div>
      </div>

      <!-- 加载状态 -->
      <div class="loading-state" v-if="loading">
        <div class="loading-spinner">
          <div class="spinner"></div>
        </div>
        <div class="loading-text">{{ loadingText }}</div>
      </div>
    </div>

    <!-- 详情弹窗 -->
    <div 
      class="mobile-modal"
      :class="{ 'show': showDetailDialog }"
      @click="closeDetailDialog"
    >
      <div class="modal-content" @click.stop>
        <!-- 详情头部 -->
        <div class="modal-header">
          <h3 class="modal-title">
            <i class="bi bi-list-ul"></i>
            任务详情 #{{ selectedMasterId }}
          </h3>
          <button class="modal-close" @click="closeDetailDialog">
            <i class="bi bi-x-lg"></i>
          </button>
        </div>

        <!-- 详情内容 -->
        <div class="modal-body">
          <div v-if="detailLoading" class="detail-loading">
            <div class="spinner"></div>
            <div>加载详情中...</div>
          </div>
          
          <div v-else-if="detailData.length > 0" class="detail-content">
            <!-- 患者列表 -->
            <div class="patient-list">
              <div 
                v-for="detail in sortedDetailData" 
                :key="detail.id"
                class="patient-card"
                :class="{ 
                  'uncontacted': (detail.contactCount || 0) === 0
                }"
                @click="showContactRecord(detail)"
              >
                <!-- 患者信息区域 -->
                <div class="patient-info">
                  <!-- 患者基本信息 -->
                  <div class="patient-header">
                    <div class="patient-name">
                      <i class="bi bi-person-fill"></i>
                      {{ detail.patName || '-' }}
                    </div>
                    <div class="patient-contact-count">
                      <span :class="getContactCountClass(detail.contactCount)">
                        {{ detail.contactCount || 0 }}次
                      </span>
                    </div>
                  </div>

                  <!-- 患者详细信息 -->
                  <div class="patient-details">
                    <div class="detail-row">
                      <span class="detail-label">性别:</span>
                      <span class="detail-value">{{ detail.sex || '-' }}</span>
                    </div>
                    <div class="detail-row">
                      <span class="detail-label">身份证:</span>
                      <span class="detail-value">{{ maskIdNumber(detail.idNumber) }}</span>
                    </div>
                    <div class="detail-row">
                      <span class="detail-label">电话:</span>
                      <span class="detail-value phone">
                        <i class="bi bi-telephone"></i>
                        {{ maskPhoneNumber(detail.phoneNumber) }}
                      </span>
                    </div>
                    <div class="detail-row">
                      <span class="detail-label">余额:</span>
                      <span class="detail-value amount">{{ formatCurrency(detail.balance) }}</span>
                    </div>
                  </div>

                  <!-- 联系状态 -->
                  <div class="contact-status">
                    <span v-if="detail.notes1" class="status-contacted">
                      <i class="bi bi-check-circle"></i>
                      {{ detail.notes1 }}
                    </span>
                    <span v-else class="status-uncontacted">
                      <i class="bi bi-dash-circle"></i>
                      未联系
                    </span>
                  </div>

                  <!-- 操作指示 -->
                  <div class="patient-action">
                    <i class="bi bi-chevron-right"></i>
                  </div>
                </div>
              </div>
            </div>
          </div>
          
          <div v-else class="detail-empty">
            <i class="bi bi-exclamation-triangle"></i>
            该任务暂无详情数据
          </div>
        </div>
      </div>
    </div>

    <!-- 联系记录弹窗 -->
    <div 
      class="mobile-modal contact-modal"
      :class="{ 'show': showContactDialog }"
      @click="closeContactDialog"
    >
      <div class="modal-content" @click.stop>
        <!-- 联系记录头部 -->
        <div class="modal-header">
          <div class="header-left">
            <div class="title-navigation-row">
              <h3 class="modal-title">
                <i class="bi bi-person-lines-fill"></i>
                {{ selectedContactDetail?.patName }}
              </h3>
              <!-- 导航按钮组 - 与姓名同行 -->
              <div class="header-navigation">
                <button 
                  class="btn btn-outline-secondary btn-xs nav-btn-header"
                  :disabled="currentContactIndex <= 0"
                  @click="prevContactRecord"
                  title="上一条联系记录"
                >
                  <i class="bi bi-chevron-left"></i>
                </button>
                <span class="nav-info-header">
                  {{ currentContactIndex + 1 }} / {{ sortedDetailData.length }}
                </span>
                <button 
                  class="btn btn-outline-secondary btn-xs nav-btn-header"
                  :disabled="currentContactIndex >= sortedDetailData.length - 1"
                  @click="nextContactRecord"
                  title="下一条联系记录"
                >
                  <i class="bi bi-chevron-right"></i>
                </button>
              </div>
            </div>
          </div>
          <div class="header-right">
            <button class="modal-close" @click="confirmCloseContactDialog">
              <i class="bi bi-x-lg"></i>
            </button>
          </div>
        </div>

        <!-- 联系记录内容 -->
        <div class="modal-body" v-if="selectedContactDetail">
          <!-- 固定信息区域 - 始终可见 -->
          <div class="fixed-info-section">
            <!-- 患者电话 - 核心信息 -->
            <div class="core-info-card">
              <div class="patient-phone-card">
                <div class="phone-icon">
                  <i class="bi bi-telephone-fill"></i>
                </div>
                <div class="phone-info">
                  <div class="phone-label">{{ selectedContactDetail.patName }}电话</div>
                  <div class="phone-number">
                    {{ formatPhoneNumber(selectedContactDetail.phoneNumber) || '暂无电话' }}
                  </div>
                </div>
                <a 
                  v-if="selectedContactDetail.phoneNumber"
                  @click="makePhoneCall(selectedContactDetail.phoneNumber, selectedContactDetail.patName, 'patient')"
                  class="phone-action-btn"
                  title="拨打患者电话"
                >
                  <i class="bi bi-telephone-outbound"></i>
                </a>
              </div>
            </div>

            <!-- 核心基本信息 - 紧凑显示 -->
            <div class="core-basic-info">
              <div class="core-info-grid">
                <div class="core-info-item">
                  <span class="core-label">性别</span>
                  <span class="core-value">{{ selectedContactDetail.sex || '-' }}</span>
                </div>
                <div class="core-info-item">
                  <span class="core-label">身份证</span>
                  <span class="core-value">{{ maskIdNumber(selectedContactDetail.idNumber) }}</span>
                </div>
              </div>
            </div>

            <!-- HIS余额 - 核心信息 -->
            <div class="core-his-balance">
              <div class="balance-header">
                <i class="bi bi-wallet2"></i>
                <span class="balance-title">HIS当前余额</span>
              </div>
              <div class="balance-content">
                <span v-if="patientBalanceLoading" class="loading">
                  <i class="bi bi-hourglass-split"></i> 查询中...
                </span>
                <span v-else-if="patientBalanceError" class="error">
                  <i class="bi bi-exclamation-triangle"></i> {{ patientBalanceError }}
                </span>
                <span v-else class="amount" :class="patientBalance > 0 ? 'positive' : 'zero'">
                  ¥{{ (patientBalance || 0).toFixed(2) }}
                </span>
              </div>
            </div>
          </div>

          <!-- 可滚动内容区域 -->
          <div class="scrollable-content">
            <!-- 详细信息折叠卡片 -->
            <div class="collapsible-card">
              <div class="card-header" @click="toggleDetailInfoExpanded">
                <div class="header-content">
                  <i class="bi bi-person-lines-fill"></i>
                  <span>详细信息</span>
                </div>
                <i :class="detailInfoExpanded ? 'bi bi-chevron-up' : 'bi bi-chevron-down'"></i>
              </div>
              
              <div v-show="detailInfoExpanded" class="card-content">
                <div class="detail-info-grid">
                  <!-- 联系人信息 -->
                  <div v-if="selectedContactDetail.nextOfKin" class="detail-info-row">
                    <span class="detail-label">联系人:</span>
                    <span class="detail-value">{{ selectedContactDetail.nextOfKin }}</span>
                  </div>
                  
                  <!-- 联系人电话 -->
                  <div v-if="selectedContactDetail.nextOfKinPhone" class="detail-info-row">
                    <span class="detail-label">联系人电话:</span>
                    <span class="detail-value phone">
                      <i class="bi bi-telephone"></i>
                      <span>{{ formatPhoneNumber(selectedContactDetail.nextOfKinPhone) }}</span>
                      <a 
                        @click="makePhoneCall(selectedContactDetail.nextOfKinPhone, selectedContactDetail.nextOfKin, 'contact')"
                        class="copy-btn-small"
                        title="拨打联系人电话"
                      >
                        <i class="bi bi-telephone-fill"></i>
                      </a>
                    </span>
                  </div>
                  
                  <!-- 监护人信息 -->
                  <div v-if="selectedContactDetail.guardianName" class="detail-info-row">
                    <span class="detail-label">监护人:</span>
                    <span class="detail-value">{{ selectedContactDetail.guardianName }}</span>
                  </div>
                  
                  <div v-if="selectedContactDetail.guardianIdcode" class="detail-info-row">
                    <span class="detail-label">监护人证件号:</span>
                    <span class="detail-value">{{ maskIdNumber(selectedContactDetail.guardianIdcode) }}</span>
                  </div>
                  
                  <!-- 余额信息 -->
                  <div class="detail-info-row">
                    <span class="detail-label">余额:</span>
                    <span class="detail-value amount">{{ formatCurrency(selectedContactDetail.balance) }}</span>
                  </div>
                </div>
              </div>
            </div>

            <!-- 快速沟通指引折叠卡片 -->
            <div class="collapsible-card">
              <div class="card-header" @click="toggleGuideExpanded">
                <div class="header-content">
                  <i class="bi bi-chat-dots"></i>
                  <span>沟通指引</span>
                </div>
                <i :class="guideExpanded ? 'bi bi-chevron-up' : 'bi bi-chevron-down'"></i>
              </div>
              
              <div v-show="guideExpanded" class="card-content">
                <!-- 沟通术语 -->
                <div class="guide-section">
                  <h6><i class="bi bi-chat-text text-primary"></i> 沟通术语</h6>
                  <div class="terms-list">
                    <div 
                      v-for="(term, index) in communicationGuide.terms" 
                      :key="index"
                      class="term-item"
                    >
                      <div class="term-title">{{ term.title }}：</div>
                      <div class="term-content">{{ term.content }}</div>
                    </div>
                  </div>
                </div>
                
                <!-- 常用话术 -->
                <div class="guide-section">
                  <h6><i class="bi bi-list-check text-success"></i> 常用话术</h6>
                  <div class="scripts-list">
                    <div 
                      v-for="(script, index) in communicationGuide.scripts" 
                      :key="index"
                      class="script-category"
                    >
                      <div class="category-title">{{ script.category }}</div>
                      <div class="script-items">
                        <div 
                          v-for="(item, itemIndex) in script.items" 
                          :key="itemIndex"
                          class="script-item"
                          @click="copyToClipboard(item)"
                        >
                          <i class="bi bi-chat-text"></i>
                          {{ item }}
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
                
                <!-- 注意事项 -->
                <div class="guide-section">
                  <h6><i class="bi bi-exclamation-triangle text-warning"></i> 注意事项</h6>
                  <div class="note-list">
                    <div 
                      v-for="(note, index) in communicationGuide.notes" 
                      :key="index" 
                      class="note-item"
                    >
                      <i class="bi bi-check-circle"></i>
                      {{ note }}
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 联系记录表单 -->
            <div class="contact-records-section">
            <div class="section-header">
              <h6>
                <i class="bi bi-clock-history"></i>
                联系记录
              </h6>
            </div>

            <!-- 联系记录列表 -->
            <div class="contact-records-list">
              <div 
                v-for="record in getContactRecords(selectedContactDetail)" 
                :key="record.index"
                class="contact-record-item"
                :class="{ 'saved': isContactRecordSaved(record.index), 'disabled': !canEditContactRecord(record.index) }"
              >
                <div class="record-header">
                  <span class="record-number">第{{ record.index }}次联系</span>
                  <span v-if="record.contactTime" class="record-time">
                    {{ formatDateTime(record.contactTime) }}
                  </span>
                </div>

                <!-- 联系结果选择 -->
                <div class="form-group">
                  <label class="form-label">联系结果</label>
                  
                  <!-- 已保存的结果 - 不可编辑 -->
                  <div v-if="isContactRecordSaved(record.index)" class="form-value saved">
                    <div class="saved-result">
                      <i class="bi bi-check-circle-fill"></i>
                      <span class="result-text">{{ record.notes }}</span>
                      <span class="saved-badge">已保存</span>
                    </div>
                  </div>
                  
                  <!-- 可编辑的选择器 - 下拉菜单形式 -->
                  <div v-else-if="canEditContactRecord(record.index) && patientBalance > 0" class="contact-result-selector">
                    <div class="result-select-container">
                      <select 
                        class="form-select contact-result-select"
                        v-model="selectedContactDetail[`notes${record.index}`]"
                        @change="onContactResultSelect(record.index)"
                      >
                        <option value="" disabled>请选择联系结果</option>
                        <option 
                          v-for="option in contactResultOptions" 
                          :key="option.id"
                          :value="option.itemName"
                        >
                          {{ option.itemName }}
                        </option>
                      </select>
                      
                      <!-- 保存按钮 - 紧跟在下拉菜单后面 -->
                      <button 
                        v-if="hasContactResultForRecord(record.index)"
                        class="btn btn-success btn-sm save-btn-inline"
                        :disabled="!canSaveContactRecord(record.index)"
                        @click="saveContactRecordForIndex(record.index)"
                      >
                        <i class="bi bi-check"></i> 保存
                      </button>
                    </div>
                  </div>
                  
                  <!-- 不可编辑状态 -->
                  <div v-else-if="patientBalance === 0" class="form-value disabled">
                    <i class="bi bi-exclamation-triangle-fill"></i> 
                    <span>患者余额为0，无法填写联系结果</span>
                  </div>
                  <div v-else class="form-value disabled">
                    <i class="bi bi-lock-fill"></i> 
                    <span>需要完成第{{ record.index - 1 }}次联系后才能填写</span>
                  </div>
                </div>

              </div>
            </div>

            <!-- 无联系记录提示 -->
            <div v-if="getContactRecords(selectedContactDetail).length === 0" class="no-records">
              <i class="bi bi-inbox"></i>
              暂无联系记录
            </div>
            
            <!-- 跳转下一条记录提示 -->
            <div v-if="showNextRecordPrompt" class="next-record-prompt">
              <div class="prompt-content">
                <div class="prompt-header">
                  <i class="bi bi-arrow-right-circle-fill text-primary"></i>
                  <span class="prompt-title">继续联系</span>
                </div>
                <div class="prompt-message">
                  是否跳转到下一条未联系的记录？
                </div>
                <div class="prompt-actions">
                  <button 
                    class="btn btn-primary btn-sm"
                    @click="goToNextUncontactedRecord"
                  >
                    <i class="bi bi-arrow-right"></i> 跳转下一条
                  </button>
                  <button 
                    class="btn btn-outline-secondary btn-sm"
                    @click="dismissNextRecordPrompt"
                  >
                    继续当前
                  </button>
                </div>
              </div>
            </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import api from '@/utils/api'
import communicationGuide from '@/config/communicationGuide'

// 响应式数据
const loading = ref(false)
const loadingText = ref('加载中...')
const masterData = ref([])
const detailData = ref([])
const detailLoading = ref(false)
const showDetailDialog = ref(false)
const showContactDialog = ref(false)
const selectedMasterId = ref(null)
const selectedContactDetail = ref(null)
const currentDetailIndex = ref(0)
const currentContactIndex = ref(0) // 当前联系记录索引
const patientBalanceLoading = ref(false)
const patientBalanceError = ref('')
const patientBalance = ref(0)
const guideExpanded = ref(false)
const detailInfoExpanded = ref(false) // 详细信息折叠状态
const latestTaskDetails = ref([])

// 网络和错误处理相关状态
const isOffline = ref(false)
const retryCount = ref(0)
const maxRetries = 3
const lastUpdateTime = ref(null)

// 路由和认证
const router = useRouter()
const authStore = useAuthStore()

// 计算属性
const canCreateNewTask = computed(() => {
  // 如果没有任何任务，可以创建（第一次创建）
  if (masterData.value.length === 0) {
    return true
  }
  
  // 如果最新任务的详情数据为空，暂时不允许创建
  if (latestTaskDetails.value.length === 0) {
    return false
  }
  
  // 检查最新任务的所有明细记录是否都有联系次数大于0
  return latestTaskDetails.value.every(detail => (detail.contactCount || 0) > 0)
})

const sortedDetailData = computed(() => {
  return [...detailData.value].sort((a, b) => {
    const aContacted = (a.contactCount || 0) > 0
    const bContacted = (b.contactCount || 0) > 0
    if (aContacted === bContacted) return 0
    return aContacted ? 1 : -1
  })
})

const uncontactedCount = computed(() => {
  return detailData.value.filter(item => (item.contactCount || 0) === 0).length
})

const contactedCount = computed(() => {
  return detailData.value.filter(item => (item.contactCount || 0) > 0).length
})

// 联系记录相关状态
const hasContactResultChanges = ref(false)
const hasUnsavedChanges = ref(false)
const originalContactData = ref({})
const contactResultOptions = ref([]) // 联系结果选项

// 跳转下一条记录提示相关状态
const showNextRecordPrompt = ref(false)
const nextRecordPromptTimer = ref(null)

// 方法
const formatDateTime = (dateStr) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const formatCurrency = (amount) => {
  if (!amount) return '¥0.00'
  return `¥${parseFloat(amount).toFixed(2)}`
}

const getProgressPercentage = (contacted, total) => {
  if (!total || total === 0) return 0
  return Math.round((contacted || 0) / total * 100)
}

const getProgressBarClass = (contacted, total) => {
  const percentage = getProgressPercentage(contacted, total)
  if (percentage === 100) return 'complete'
  if (percentage >= 50) return 'good'
  if (percentage > 0) return 'started'
  return 'none'
}

const getContactCountClass = (count) => {
  if (!count || count === 0) return 'badge bg-warning'
  return 'badge bg-success'
}

const maskIdNumber = (idNumber) => {
  if (!idNumber) return '-'
  if (idNumber.length <= 8) return idNumber
  return idNumber.substring(0, 4) + '****' + idNumber.substring(idNumber.length - 4)
}

const maskPhoneNumber = (phone) => {
  if (!phone) return '-'
  if (phone.length <= 7) return phone
  return phone.substring(0, 3) + '****' + phone.substring(phone.length - 4)
}

const formatPhoneNumber = (phone) => {
  if (!phone) return ''
  return phone.replace(/(\d{3})(\d{4})(\d{4})/, '$1-$2-$3')
}

const copyPhoneNumber = async (phone) => {
  try {
    await navigator.clipboard.writeText(phone)
    // 简单的提示
    alert('电话号码已复制')
  } catch (err) {
    console.error('复制失败:', err)
  }
}

const copyToClipboard = async (text) => {
  try {
    await navigator.clipboard.writeText(text)
    alert('已复制到剪贴板')
  } catch (err) {
    console.error('复制失败:', err)
  }
}

const toggleGuideExpanded = () => {
  guideExpanded.value = !guideExpanded.value
}

const toggleDetailInfoExpanded = () => {
  detailInfoExpanded.value = !detailInfoExpanded.value
}

// 网络状态检测
const checkNetworkStatus = () => {
  isOffline.value = !navigator.onLine
}

// 错误重试机制
const retryOperation = async (operation, operationName = '操作') => {
  for (let i = 0; i <= maxRetries; i++) {
    try {
      retryCount.value = i
      const result = await operation()
      retryCount.value = 0
      return result
    } catch (error) {
      console.error(`${operationName}失败 (第${i + 1}次尝试):`, error)
      
      if (i === maxRetries) {
        retryCount.value = 0
        throw new Error(`${operationName}失败，已重试${maxRetries}次。请检查网络连接后重试。`)
      }
      
      // 等待递增的时间后重试
      await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1)))
    }
  }
}

// API 调用方法
const loadMasterData = async () => {
  try {
    // 检查用户登录状态
    if (!authStore.isAuthenticated || !authStore.user) {
      alert('用户未登录，请先登录')
      return
    }

    loading.value = true
    loadingText.value = '加载退费任务数据...'
    
    // 使用重试机制加载数据
    await retryOperation(async () => {
      const response = await api.post('/api/RefundTaskMaster/get-by-username', {
        username: authStore.user.username
      })
      
      masterData.value = response.data || []
      lastUpdateTime.value = new Date()
      
      // 为每个任务加载联系统计数信息
      if (masterData.value.length > 0) {
        await loadContactStatsForAllTasks()
        await loadLatestTaskDetails()
      } else {
        latestTaskDetails.value = []
      }
    }, '加载主表数据')
    
  } catch (error) {
    console.error('加载主表数据失败:', error)
    alert(error.message || '加载数据失败，请重试')
  } finally {
    loading.value = false
  }
}

// 为所有任务加载联系统计数信息
const loadContactStatsForAllTasks = async () => {
  try {
    // 并行加载所有任务的详情数据来计算联系统计数
    const promises = masterData.value.map(async (task) => {
      try {
        const response = await api.post('/api/RefundTaskDetail/get-by-master-id', {
          id: task.id
        })
        
        const details = response.data || []
        // 计算已联系的患者数量（联系次数大于0）
        const contactedCount = details.filter(detail => (detail.contactCount || 0) > 0).length
        
        // 将联系统计数信息添加到任务对象中
        task.contactedCount = contactedCount
        
        return task
      } catch (error) {
        console.error(`加载任务 ${task.id} 的详情失败:`, error)
        // 如果加载失败，设置默认值
        task.contactedCount = 0
        return task
      }
    })
    
    await Promise.all(promises)
  } catch (error) {
    console.error('加载联系统计数信息失败:', error)
  }
}

// 优化：直接更新前端联系统计数，避免重复调用接口
const updateContactStatsForTask = (masterId, contactCountChange = 0) => {
  const task = masterData.value.find(t => t.id === masterId)
  if (task) {
    // 如果联系次数增加，则已联系患者数量也增加
    if (contactCountChange > 0) {
      task.contactedCount = (task.contactedCount || 0) + 1
    }
  }
}

// 加载最新任务的详情数据
const loadLatestTaskDetails = async () => {
  try {
    if (masterData.value.length === 0) {
      latestTaskDetails.value = []
      return
    }
    
    // 获取最新的任务（按创建时间排序，取第一个）
    const latestTask = masterData.value.reduce((latest, current) => {
      const latestDate = new Date(latest.inputDate)
      const currentDate = new Date(current.inputDate)
      return currentDate > latestDate ? current : latest
    })
    
    // 加载最新任务的详情数据
    const response = await api.post('/api/RefundTaskDetail/get-by-master-id', {
      id: latestTask.id
    })
    
    latestTaskDetails.value = response.data || []
  } catch (error) {
    console.error('加载最新任务详情失败:', error)
    latestTaskDetails.value = []
  }
}

const createRefundTask = async () => {
  if (!canCreateNewTask.value) {
    const uncontactedCount = latestTaskDetails.value.filter(detail => (detail.contactCount || 0) === 0).length
    alert(`当前任务中还有 ${uncontactedCount} 位患者未联系，请先完成联系工作后再创建新任务`)
    return
  }
  
  try {
    loading.value = true
    loadingText.value = '创建退费任务中...'
    
    // 构建请求数据
    const requestData = {
      username: authStore.user?.username,
      fullname: authStore.user?.fullName || authStore.user?.username,
      accountCount: 0,
      accountSumBalance: 0
    }
    
    const response = await api.post('/api/RefundTaskMaster/create-with-his-data', requestData)
    
    // 与Web端保持一致的响应数据处理
    if (response.data && response.data.id) {
      alert('退费任务创建成功！已从HIS数据库导入数据')
      await loadMasterData()
    } else {
      alert('创建失败: ' + (response.data?.message || '未知错误'))
    }
  } catch (error) {
    console.error('创建任务失败:', error)
    alert('创建失败: ' + (error.response?.data?.message || error.message))
  } finally {
    loading.value = false
  }
}

const showDetails = async (masterId) => {
  selectedMasterId.value = masterId
  showDetailDialog.value = true
  
  try {
    detailLoading.value = true
    
    await retryOperation(async () => {
      const response = await api.post('/api/RefundTaskDetail/get-by-master-id', { id: masterId })
      
      if (response.data) {
        detailData.value = response.data || []
        // 对身份证和电话号码进行脱敏处理
        detailData.value.forEach(item => {
          if (item.idNumber) {
            item.maskedIdNumber = maskIdNumber(item.idNumber)
          }
          if (item.phoneNumber) {
            item.maskedPhoneNumber = maskPhoneNumber(item.phoneNumber)
          }
        })
      } else {
        throw new Error('未获取到数据')
      }
    }, '加载详情')
    
  } catch (error) {
    console.error('加载详情失败:', error)
    alert(error.message || '加载详情失败，请重试')
  } finally {
    detailLoading.value = false
  }
}

const showContactRecord = async (detail) => {
  selectedContactDetail.value = detail
  showContactDialog.value = true
  
  // 设置当前联系记录索引
  const index = sortedDetailData.value.findIndex(item => item.id === detail.id)
  currentContactIndex.value = index !== -1 ? index : 0
  
  // 保存原始数据用于变更检测
  originalContactData.value = { ...detail }
  hasContactResultChanges.value = false
  hasUnsavedChanges.value = false
  
  // 加载联系结果字典数据
  await loadContactResultOptions()
  
  // 查询HIS余额 - 使用正确的接口
  if (detail.patientId) {
    try {
      patientBalanceLoading.value = true
      patientBalanceError.value = ''
      patientBalance.value = 0
      
      const response = await api.get(`/api/refund/patient-balance/${detail.patientId}`)
      
      if (response.data && response.data.success) {
        patientBalance.value = response.data.data.balance || 0
      } else {
        patientBalanceError.value = response.data?.message || '查询余额失败'
      }
    } catch (error) {
      console.error('查询患者余额失败:', error)
      patientBalanceError.value = '查询余额失败: ' + (error.response?.data?.message || error.message)
    } finally {
      patientBalanceLoading.value = false
    }
  }
  
  // 检查初始状态，确保保存按钮状态正确
  checkForChanges()
}

const closeDetailDialog = () => {
  showDetailDialog.value = false
  selectedMasterId.value = null
  detailData.value = []
}

const closeContactDialog = () => {
  // 检查是否有未保存的更改
  if (hasContactResultChanges.value) {
    const confirmClose = confirm('您有未保存的联系记录更改，确定要退出吗？\n点击"确定"退出并丢弃更改，点击"取消"继续编辑。')
    if (!confirmClose) {
      return // 用户选择继续编辑，不关闭弹窗
    }
  }
  
  showContactDialog.value = false
  selectedContactDetail.value = null
  patientBalance.value = 0
  patientBalanceError.value = ''
  hasContactResultChanges.value = false
  hasUnsavedChanges.value = false
  originalContactData.value = {}
}

// 确认关闭联系记录弹窗
const confirmCloseContactDialog = () => {
  // 检查是否有未保存的更改
  if (hasContactResultChanges.value) {
    const confirmClose = confirm('您有未保存的联系记录更改，确定要关闭吗？\n\n点击"确定"关闭并丢弃更改\n点击"取消"继续编辑')
    if (!confirmClose) {
      return // 用户选择继续编辑，不关闭弹窗
    }
  } else {
    // 没有未保存更改时，也给一个简单的确认提示
    const confirmClose = confirm('确定要关闭联系记录吗？')
    if (!confirmClose) {
      return
    }
  }
  
  // 执行关闭操作
  closeContactDialog()
}

// 导航到上一条联系记录
const prevContactRecord = async () => {
  // 检查是否有未保存的更改
  if (hasContactResultChanges.value) {
    const confirmSwitch = confirm('您有未保存的联系记录更改，确定要切换到上一条记录吗？\n点击"确定"切换并丢弃更改，点击"取消"继续编辑。')
    if (!confirmSwitch) {
      return
    }
  }
  
  if (currentContactIndex.value > 0) {
    const prevDetail = sortedDetailData.value[currentContactIndex.value - 1]
    await showContactRecord(prevDetail)
  }
}

// 导航到下一条联系记录
const nextContactRecord = async () => {
  // 检查是否有未保存的更改
  if (hasContactResultChanges.value) {
    const confirmSwitch = confirm('您有未保存的联系记录更改，确定要切换到下一条记录吗？\n点击"确定"切换并丢弃更改，点击"取消"继续编辑。')
    if (!confirmSwitch) {
      return
    }
  }
  
  if (currentContactIndex.value < sortedDetailData.value.length - 1) {
    const nextDetail = sortedDetailData.value[currentContactIndex.value + 1]
    await showContactRecord(nextDetail)
  }
}

// 联系记录相关函数
const getContactRecords = (detail) => {
  if (!detail) return []
  
  const records = []
  for (let i = 1; i <= 5; i++) {
    const notes = detail[`notes${i}`]
    const userNotes = detail[`userNotes${i}`]
    const contactTime = detail[`contactTime${i}`]
    
    records.push({
      index: i,
      notes: notes || '',
      userNotes: userNotes || '',
      contactTime: contactTime
    })
  }
  
  return records
}

const isContactRecordSaved = (index) => {
  if (!selectedContactDetail.value || !originalContactData.value) return false
  
  // 检查原始数据中是否有这个联系记录（即已保存到数据库的）
  const originalNotes = originalContactData.value[`notes${index}`]
  const originalContactTime = originalContactData.value[`contactTime${index}`]
  
  // 只有原始数据中有联系结果和联系时间，才认为是已保存的
  return originalNotes && originalNotes.trim() !== '' && originalContactTime
}

const canEditContactRecord = (index) => {
  if (!selectedContactDetail.value || patientBalance.value === 0) return false
  
  // 第一次联系总是可以编辑
  if (index === 1) return true
  
  // 其他次数需要前一次已经保存
  return isContactRecordSaved(index - 1)
}

const onContactResultChange = (index) => {
  checkForChanges()
}

const onContactResultSelect = (index) => {
  checkForChanges()
  
  // 跟踪用户行为
  try {
    const selectedResult = selectedContactDetail.value[`notes${index}`]
    if (selectedResult && userBehaviorService) {
      userBehaviorService.trackSelectResult(selectedResult)
    }
  } catch (error) {
    console.warn('跟踪选择联系结果失败:', error)
  }
}

const selectContactResult = (index, resultValue) => {
  if (!selectedContactDetail.value) return
  
  // 设置选中的联系结果
  selectedContactDetail.value[`notes${index}`] = resultValue
  
  // 检查变化
  checkForChanges()
}

const checkForChanges = () => {
  if (!selectedContactDetail.value) return
  
  // 检查联系结果的变化
  let hasChanges = false
  let hasUnsavedResults = false
  
  for (let i = 1; i <= 5; i++) {
    const currentNotes = selectedContactDetail.value[`notes${i}`] || ''
    const originalNotes = originalContactData.value[`notes${i}`] || ''
    
    // 检查是否有变化
    if (currentNotes !== originalNotes) {
      hasChanges = true
    }
    
    // 检查是否有未保存的联系结果（当前有联系结果但原始数据中没有保存到数据库）
    if (currentNotes && currentNotes.trim() !== '') {
      const originalContactTime = originalContactData.value[`contactTime${i}`]
      // 如果有联系结果但没有对应的联系时间，说明是未保存的
      if (!originalContactTime) {
        hasUnsavedResults = true
      }
    }
  }
  
  // 只要有变化或者有未保存的联系结果，就允许保存
  hasContactResultChanges.value = hasChanges || hasUnsavedResults
  hasUnsavedChanges.value = hasChanges || hasUnsavedResults
}

const saveContactRecord = async () => {
  if (!selectedContactDetail.value) return
  
  // 检查患者余额
  if (patientBalance.value === 0) {
    alert('患者余额为0，无法保存联系记录')
    return
  }
  
  // 检查是否有联系结果的变化
  if (!hasContactResultChanges.value) {
    alert('请选择联系结果后再保存')
    return
  }
  
  try {
    loading.value = true
    loadingText.value = '保存联系记录中...'
    
    await retryOperation(async () => {
      // 获取当前时间，格式化为 ISO 字符串
      const currentTime = new Date().toISOString();
      
      // 计算实际的联系次数 - 根据填写的notes数量
      let actualContactCount = 0;
      const notesFields = ['notes1', 'notes2', 'notes3', 'notes4', 'notes5'];
      for (const field of notesFields) {
        if (selectedContactDetail.value[field] && selectedContactDetail.value[field].trim() !== '') {
          actualContactCount++;
        }
      }
      
      // 构建更新请求数据，包含完整的记录信息
      const updateData = {
        id: selectedContactDetail.value.id,
        masterId: selectedContactDetail.value.masterId,
        patientId: selectedContactDetail.value.patientId,
        accountId: selectedContactDetail.value.accountId,
        accountIndex: selectedContactDetail.value.accountIndex,
        balance: selectedContactDetail.value.balance,
        contactCount: actualContactCount, // 使用计算出的实际联系次数
        phoneNumber: selectedContactDetail.value.phoneNumber,
        patName: selectedContactDetail.value.patName,
        idNumber: selectedContactDetail.value.idNumber,
        sex: selectedContactDetail.value.sex,
        nextOfKin: selectedContactDetail.value.nextOfKin,
        // 联系记录字段 - 如果有联系结果则自动设置当前时间
        contactTime1: selectedContactDetail.value.contactTime1 || (selectedContactDetail.value.notes1 ? currentTime : null),
        notes1: selectedContactDetail.value.notes1,
        userNotes1: '',
        contactTime2: selectedContactDetail.value.contactTime2 || (selectedContactDetail.value.notes2 ? currentTime : null),
        notes2: selectedContactDetail.value.notes2,
        userNotes2: '',
        contactTime3: selectedContactDetail.value.contactTime3 || (selectedContactDetail.value.notes3 ? currentTime : null),
        notes3: selectedContactDetail.value.notes3,
        userNotes3: '',
        contactTime4: selectedContactDetail.value.contactTime4 || (selectedContactDetail.value.notes4 ? currentTime : null),
        notes4: selectedContactDetail.value.notes4,
        userNotes4: '',
        contactTime5: selectedContactDetail.value.contactTime5 || (selectedContactDetail.value.notes5 ? currentTime : null),
        notes5: selectedContactDetail.value.notes5,
        userNotes5: ''
      };

      // 调用正确的后台接口
      const response = await api.post('/api/RefundTaskDetail/update', updateData);

      if (response.data) {
        // 更新原始数据备份
        originalContactData.value = JSON.parse(JSON.stringify(selectedContactDetail.value))
        hasUnsavedChanges.value = false
        hasContactResultChanges.value = false
        
        // 更新详情数据中的对应记录
        const detailIndex = detailData.value.findIndex(item => item.id === selectedContactDetail.value.id);
        if (detailIndex !== -1) {
          Object.assign(detailData.value[detailIndex], updateData);
          // 同时更新当前显示的联系详情
          Object.assign(selectedContactDetail.value, updateData);
        }
        
        // 优化：直接更新前端联系统计数，避免重复调用接口
        // 检查是否是第一次保存联系记录（从0次变为有联系记录）
        const wasUncontacted = (originalContactData.value.contactCount || 0) === 0
        const nowContacted = actualContactCount > 0
        if (wasUncontacted && nowContacted) {
          updateContactStatsForTask(selectedContactDetail.value.masterId, 1)
        }
        
        // 显示跳转下一条记录的提示
        showNextRecordPromptWithDelay()
        
      } else {
        throw new Error('保存失败');
      }
    }, '保存联系记录')
    
  } catch (error) {
    console.error('保存联系记录失败:', error)
    alert(error.message || '保存联系记录失败，请重试')
  } finally {
    loading.value = false
  }
}

// 单个联系记录保存相关方法
const hasContactResultForRecord = (index) => {
  if (!selectedContactDetail.value) return false
  const notes = selectedContactDetail.value[`notes${index}`]
  return notes && notes.trim() !== ''
}

const canSaveContactRecord = (index) => {
  if (!selectedContactDetail.value || patientBalance.value === 0) return false
  
  // 检查该记录是否已经保存
  if (isContactRecordSaved(index)) return false
  
  // 检查是否有联系结果
  const notes = selectedContactDetail.value[`notes${index}`]
  if (!notes || notes.trim() === '') return false
  
  // 检查是否可以编辑该记录
  return canEditContactRecord(index)
}

const hasUnsavedChangesForRecord = (index) => {
  if (!selectedContactDetail.value) return false
  
  const notes = selectedContactDetail.value[`notes${index}`]
  const originalNotes = originalContactData.value[`notes${index}`]
  
  // 如果有联系结果但与原始数据不同，说明有未保存的更改
  return notes && notes.trim() !== '' && notes !== originalNotes
}

const saveContactRecordForIndex = async (index) => {
  if (!selectedContactDetail.value || !canSaveContactRecord(index)) return
  
  try {
    loading.value = true
    loadingText.value = `保存第${index}次联系记录中...`
    
    await retryOperation(async () => {
      // 获取当前时间，格式化为 ISO 字符串
      const currentTime = new Date().toISOString();
      
      // 计算实际的联系次数 - 根据填写的notes数量
      let actualContactCount = 0;
      const notesFields = ['notes1', 'notes2', 'notes3', 'notes4', 'notes5'];
      for (const field of notesFields) {
        if (selectedContactDetail.value[field] && selectedContactDetail.value[field].trim() !== '') {
          actualContactCount++;
        }
      }
      
      // 构建更新请求数据，只更新指定的联系记录
      const updateData = {
        id: selectedContactDetail.value.id,
        masterId: selectedContactDetail.value.masterId,
        patientId: selectedContactDetail.value.patientId,
        accountId: selectedContactDetail.value.accountId,
        accountIndex: selectedContactDetail.value.accountIndex,
        balance: selectedContactDetail.value.balance,
        contactCount: actualContactCount,
        phoneNumber: selectedContactDetail.value.phoneNumber,
        patName: selectedContactDetail.value.patName,
        idNumber: selectedContactDetail.value.idNumber,
        sex: selectedContactDetail.value.sex,
        nextOfKin: selectedContactDetail.value.nextOfKin,
        // 保持所有现有的联系记录
        contactTime1: selectedContactDetail.value.contactTime1,
        notes1: selectedContactDetail.value.notes1,
        userNotes1: selectedContactDetail.value.userNotes1 || '',
        contactTime2: selectedContactDetail.value.contactTime2,
        notes2: selectedContactDetail.value.notes2,
        userNotes2: selectedContactDetail.value.userNotes2 || '',
        contactTime3: selectedContactDetail.value.contactTime3,
        notes3: selectedContactDetail.value.notes3,
        userNotes3: selectedContactDetail.value.userNotes3 || '',
        contactTime4: selectedContactDetail.value.contactTime4,
        notes4: selectedContactDetail.value.notes4,
        userNotes4: selectedContactDetail.value.userNotes4 || '',
        contactTime5: selectedContactDetail.value.contactTime5,
        notes5: selectedContactDetail.value.notes5,
        userNotes5: selectedContactDetail.value.userNotes5 || ''
      };

      // 为指定的联系记录设置时间（如果还没有时间的话）
      if (!selectedContactDetail.value[`contactTime${index}`]) {
        updateData[`contactTime${index}`] = currentTime;
        selectedContactDetail.value[`contactTime${index}`] = currentTime;
      }

      // 调用后台接口
      const response = await api.post('/api/RefundTaskDetail/update', updateData);

      if (response.data) {
        // 更新原始数据备份中的对应字段
        originalContactData.value[`notes${index}`] = selectedContactDetail.value[`notes${index}`]
        originalContactData.value[`contactTime${index}`] = selectedContactDetail.value[`contactTime${index}`]
        
        // 重新检查变化状态
        checkForChanges()
        
        // 更新详情数据中的对应记录
        const detailIndex = detailData.value.findIndex(item => item.id === selectedContactDetail.value.id);
        if (detailIndex !== -1) {
          Object.assign(detailData.value[detailIndex], updateData);
        }
        
        // 优化：直接更新前端联系统计数，避免重复调用接口
        // 检查是否是第一次保存联系记录（从0次变为有联系记录）
        const wasUncontacted = (originalContactData.value.contactCount || 0) === 0
        const nowContacted = actualContactCount > 0
        if (wasUncontacted && nowContacted) {
          updateContactStatsForTask(selectedContactDetail.value.masterId, 1)
        }
        
        // 显示跳转下一条记录的提示
        showNextRecordPromptWithDelay()
        
      } else {
        throw new Error('保存失败');
      }
    }, `保存第${index}次联系记录`)
    
  } catch (error) {
    console.error(`保存第${index}次联系记录失败:`, error)
    alert(error.message || `保存第${index}次联系记录失败，请重试`)
  } finally {
    loading.value = false
  }
}

// 跳转下一条记录相关方法
const showNextRecordPromptWithDelay = () => {
  // 清除之前的定时器
  if (nextRecordPromptTimer.value) {
    clearTimeout(nextRecordPromptTimer.value)
  }
  
  // 延迟显示提示，避免界面闪烁
  nextRecordPromptTimer.value = setTimeout(() => {
    // 检查是否还有未联系的记录
    const nextUncontactedRecord = findNextUncontactedRecord()
    if (nextUncontactedRecord) {
      showNextRecordPrompt.value = true
      
      // 5秒后自动隐藏提示
      setTimeout(() => {
        if (showNextRecordPrompt.value) {
          dismissNextRecordPrompt()
        }
      }, 5000)
    }
  }, 1000)
}

const findNextUncontactedRecord = () => {
  // 在当前任务的详情数据中查找下一条未联系的记录
  const uncontactedRecords = detailData.value.filter(detail => (detail.contactCount || 0) === 0)
  
  if (uncontactedRecords.length > 0) {
    // 返回第一条未联系的记录
    return uncontactedRecords[0]
  }
  
  return null
}

const goToNextUncontactedRecord = async () => {
  const nextRecord = findNextUncontactedRecord()
  if (nextRecord) {
    // 隐藏提示
    dismissNextRecordPrompt()
    
    // 跳转到下一条记录
    await showContactRecord(nextRecord)
  }
}

const dismissNextRecordPrompt = () => {
  showNextRecordPrompt.value = false
  if (nextRecordPromptTimer.value) {
    clearTimeout(nextRecordPromptTimer.value)
    nextRecordPromptTimer.value = null
  }
}

// 加载联系结果字典数据
const loadContactResultOptions = async () => {
  try {
    const response = await api.post('/api/Dict/get-by-dict-id', {
      dictId: 7
    })
    
    if (response.data && Array.isArray(response.data)) {
      contactResultOptions.value = response.data
    } else {
      contactResultOptions.value = []
      console.warn('联系结果字典数据格式不正确:', response.data)
    }
  } catch (error) {
    console.error('获取联系结果选项失败:', error)
    contactResultOptions.value = []
  }
}

const refreshData = async () => {
  await loadMasterData()
}

// 拨打电话并记录通话日志
const makePhoneCall = async (phoneNumber, contactName = '', callType = 'phone') => {
  try {
    // 获取当前用户信息
    const userInfo = authStore.user
    
    // 准备通话记录数据
    const callLogData = {
      username: userInfo?.username || '',
      fullname: userInfo?.fullname || userInfo?.username || '',
      callPhone: phoneNumber,
      userPhone: userInfo?.phone || '',
      sendMsg: callType === 'patient' 
        ? `拨打患者电话 - 患者姓名: ${contactName || ''}, 身份证: ${selectedContactDetail.value?.idNumber || ''}` 
        : callType === 'contact'
        ? `拨打联系人电话 - 联系人: ${contactName || ''}, 患者: ${selectedContactDetail.value?.patName || ''}`
        : `拨打电话: ${phoneNumber}`
    }
    
    // 调用 CallLog API 保存通话记录
    try {
      await api.post('/api/CallLog/create', callLogData)
      console.log('通话记录已保存:', callLogData)
    } catch (error) {
      console.error('保存通话记录失败:', error)
      // 即使保存失败也继续拨打电话
    }
    
    // 拨打电话
    window.location.href = `tel:${phoneNumber}`
    
  } catch (error) {
    console.error('拨打电话失败:', error)
    // 如果出错，仍然尝试拨打电话
    window.location.href = `tel:${phoneNumber}`
  }
}

const logout = () => {
  authStore.logout()
  router.push('/login')
}

// 生命周期
onMounted(() => {
  loadMasterData()
  
  // 监听网络状态变化
  window.addEventListener('online', () => {
    isOffline.value = false
    checkNetworkStatus()
  })
  
  window.addEventListener('offline', () => {
    isOffline.value = true
  })
  
  // 初始检查网络状态
  checkNetworkStatus()
})
</script>

<style scoped>
/* 移动端专用样式 */
.mobile-refund-task {
  min-height: 100vh;
  background: #f8f9fa;
  padding-bottom: env(safe-area-inset-bottom);
}

/* 顶部导航栏 */
.mobile-header {
  background: linear-gradient(135deg, #007bff, #0056b3);
  color: white;
  padding: 1rem;
  padding-top: calc(1rem + env(safe-area-inset-top));
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  font-size: 1.25rem;
  font-weight: 600;
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 0.5rem;
}

.header-actions .btn {
  border-radius: 50%;
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0;
}

/* 主要内容区域 */
.mobile-content {
  padding: 1rem;
}

/* 创建任务区域 */
.create-task-section {
  margin-bottom: 1.5rem;
}

.create-task-btn {
  border-radius: 12px;
  padding: 1rem;
  font-size: 1.1rem;
  font-weight: 600;
  box-shadow: 0 4px 12px rgba(0,123,255,0.3);
}

.create-tip {
  margin-top: 1rem;
}

.create-tip .alert {
  border-radius: 8px;
  font-size: 0.9rem;
}

/* 任务卡片 */
.task-list {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.task-card {
  background: white;
  border-radius: 12px;
  padding: 1rem;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
}

.task-card:active {
  transform: scale(0.98);
  box-shadow: 0 1px 4px rgba(0,0,0,0.1);
}

.task-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
}

.task-id {
  font-weight: 600;
  color: #007bff;
  font-size: 1.1rem;
}

.task-date {
  font-size: 0.85rem;
  color: #6c757d;
}

/* 进度条 */
.task-progress {
  margin-bottom: 1rem;
}

.progress-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0.5rem;
}

.progress-text {
  font-size: 0.9rem;
  color: #495057;
}

.progress-numbers {
  font-weight: 600;
  color: #007bff;
}

.progress-bar-container {
  height: 8px;
  background: #e9ecef;
  border-radius: 4px;
  overflow: hidden;
  margin-bottom: 0.25rem;
}

.progress-bar-fill {
  height: 100%;
  transition: width 0.3s ease;
  border-radius: 4px;
}

.progress-bar-fill.none {
  background: #dc3545;
}

.progress-bar-fill.started {
  background: #ffc107;
}

.progress-bar-fill.good {
  background: #17a2b8;
}

.progress-bar-fill.complete {
  background: #28a745;
}

.progress-percentage {
  text-align: right;
  font-size: 0.8rem;
  color: #6c757d;
}

/* 统计信息 */
.task-stats {
  display: flex;
  gap: 1rem;
  margin-bottom: 1rem;
}

.stat-item {
  flex: 1;
  text-align: center;
  padding: 0.5rem;
  background: #f8f9fa;
  border-radius: 8px;
}

.stat-label {
  font-size: 0.8rem;
  color: #6c757d;
  margin-bottom: 0.25rem;
}

.stat-value {
  font-weight: 600;
  font-size: 1rem;
}

.stat-value.amount {
  color: #28a745;
}

/* 备注 */
.task-notes {
  font-size: 0.9rem;
  color: #6c757d;
  background: #f8f9fa;
  padding: 0.5rem;
  border-radius: 6px;
  margin-bottom: 0.5rem;
}

/* 操作指示 */
.task-action {
  position: absolute;
  right: 1rem;
  top: 50%;
  transform: translateY(-50%);
  color: #6c757d;
  font-size: 1.2rem;
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 3rem 1rem;
  color: #6c757d;
}

.empty-icon {
  font-size: 4rem;
  margin-bottom: 1rem;
  opacity: 0.5;
}

.empty-title {
  font-size: 1.2rem;
  font-weight: 600;
  margin-bottom: 0.5rem;
}

.empty-subtitle {
  font-size: 0.9rem;
}

/* 加载状态 */
.loading-state {
  text-align: center;
  padding: 3rem 1rem;
}

.loading-spinner {
  margin-bottom: 1rem;
}

.spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #e9ecef;
  border-top: 4px solid #007bff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text {
  color: #6c757d;
  font-size: 0.9rem;
}

/* 移动端弹窗 */
.mobile-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.5);
  z-index: 1000;
  display: flex;
  align-items: flex-end;
  opacity: 0;
  visibility: hidden;
  transition: all 0.3s ease;
}

.mobile-modal.show {
  opacity: 1;
  visibility: visible;
}

.modal-content {
  background: white;
  width: 100%;
  max-height: 90vh;
  border-radius: 16px 16px 0 0;
  transform: translateY(100%);
  transition: transform 0.3s ease;
  display: flex;
  flex-direction: column;
}

.mobile-modal.show .modal-content {
  transform: translateY(0);
}

.modal-header {
  padding: 1rem;
  border-bottom: 1px solid #e9ecef;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-shrink: 0;
  gap: 1rem;
}

.header-left {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
  flex: 1;
  min-width: 0;
}

.title-navigation-row {
  display: flex;
  align-items: center;
  gap: 1rem;
  height: 40px; /* 统一高度 */
}

.header-right {
  flex-shrink: 0;
  margin-left: 1rem;
}

.modal-title {
  font-size: 1.1rem;
  font-weight: 600;
  margin: 0;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  height: 40px; /* 与导航组统一高度 */
  display: flex;
  align-items: center;
  flex-shrink: 0;
}

.header-navigation {
  display: flex;
  align-items: center;
  gap: 0.25rem;
  background: #f8f9fa;
  border: 1px solid #dee2e6;
  border-radius: 6px;
  padding: 0.25rem 0.5rem;
  height: 40px; /* 与标题统一高度 */
  flex-shrink: 0;
}

.nav-btn-header {
  background: white;
  border: 1px solid #dee2e6;
  color: #6c757d;
  padding: 0.25rem 0.5rem;
  border-radius: 4px;
  font-size: 0.75rem;
  min-width: 28px;
  height: 28px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
}

.nav-btn-header:hover:not(:disabled) {
  background: #e9ecef;
  border-color: #adb5bd;
  color: #495057;
}

.nav-btn-header:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.nav-info-header {
  font-size: 0.75rem;
  color: #6c757d;
  padding: 0 0.5rem;
  font-weight: 500;
  white-space: nowrap;
}

.modal-close {
  background: none;
  border: none;
  font-size: 1.2rem;
  color: #6c757d;
  padding: 0.5rem;
  border-radius: 50%;
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
}

.modal-close:hover {
  background: #f8f9fa;
  color: #495057;
}

.modal-body {
  padding: 1rem;
  overflow-y: auto;
  flex: 1;
}

/* 详情统计 */
.detail-stats {
  display: flex;
  gap: 1rem;
  margin-bottom: 1.5rem;
}

.stat-card {
  flex: 1;
  text-align: center;
  padding: 1rem;
  background: #f8f9fa;
  border-radius: 8px;
}

.stat-number {
  font-size: 1.5rem;
  font-weight: 700;
  margin-bottom: 0.25rem;
}

.stat-label {
  font-size: 0.8rem;
  color: #6c757d;
}

/* 患者卡片 */
.patient-list {
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
}

.patient-card {
  background: white;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  padding: 1rem;
  cursor: pointer;
  transition: all 0.2s ease;
  position: relative;
}

.patient-card.uncontacted {
  border-left: 4px solid #ffc107;
  background: #fffbf0;
}

.patient-card:active {
  transform: scale(0.98);
}

.patient-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0.75rem;
}

.patient-name {
  font-weight: 600;
  font-size: 1rem;
  color: #495057;
}

.patient-contact-count .badge {
  font-size: 0.75rem;
}

.patient-details {
  margin-bottom: 0.75rem;
}

.detail-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 0.25rem;
  font-size: 0.9rem;
}

.detail-label {
  color: #6c757d;
  min-width: 60px;
}

.detail-value {
  color: #495057;
  text-align: right;
}

.detail-value.phone {
  color: #007bff;
}

.detail-value.amount {
  color: #28a745;
  font-weight: 600;
}

.contact-status {
  margin-bottom: 0.5rem;
}

.status-contacted {
  color: #28a745;
  font-size: 0.9rem;
}

.status-uncontacted {
  color: #6c757d;
  font-size: 0.9rem;
}

.patient-action {
  position: absolute;
  right: 1rem;
  top: 50%;
  transform: translateY(-50%);
  color: #6c757d;
}

/* 联系记录相关样式 */
.contact-records-section {
  background: white;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  overflow: hidden;
}

.section-header {
  padding: 1rem;
  background: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.section-header h6 {
  margin: 0;
  font-weight: 600;
  color: #495057;
}

/* 导航按钮和保存按钮布局样式 */
.action-buttons {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 1rem;
}

.navigation-group {
  display: flex;
  align-items: center;
  gap: 0.25rem;
  background: #f8f9fa;
  border: 1px solid #dee2e6;
  border-radius: 4px;
  padding: 0.15rem 0.3rem;
  margin-right: auto;
}

.nav-btn {
  min-width: 28px;
  height: 28px;
  padding: 0.15rem;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 3px;
  font-size: 0.8rem;
  border: 1px solid #dee2e6;
  background: white;
  transition: all 0.2s ease;
}

.nav-btn:hover:not(:disabled) {
  background: #e9ecef;
  border-color: #adb5bd;
}

.nav-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.nav-info {
  font-size: 0.75rem;
  font-weight: 600;
  color: #495057;
  padding: 0 0.15rem;
  white-space: nowrap;
  min-width: 35px;
  text-align: center;
}

.save-btn.btn.btn-success {
  font-size: 1.1rem !important;
  padding: 1rem 2rem !important;
  font-weight: 600 !important;
  border-radius: 8px !important;
  min-height: 48px !important;
  min-width: 140px !important;
  width: auto !important;
  display: inline-flex !important;
  align-items: center !important;
  justify-content: center !important;
  gap: 0.5rem !important;
  transition: all 0.2s ease !important;
  box-shadow: 0 2px 8px rgba(40, 167, 69, 0.2) !important;
  white-space: nowrap !important;
}

.save-btn.btn.btn-success:hover:not(:disabled) {
  transform: translateY(-1px) !important;
  box-shadow: 0 4px 12px rgba(40, 167, 69, 0.3) !important;
}

.save-section .btn {
  font-size: 0.9rem;
  padding: 0.5rem 1rem;
}

.save-status {
  padding: 0.75rem 1rem;
  border-bottom: 1px solid #e9ecef;
}

.status-message {
  font-size: 0.9rem;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.status-message.success {
  color: #28a745;
}

.status-message.warning {
  color: #ffc107;
}

.contact-records-list {
  padding: 1rem;
}

.contact-record-item {
  border: 1px solid #e9ecef;
  border-radius: 8px;
  padding: 1rem;
  margin-bottom: 1rem;
  background: #fafafa;
}

.contact-record-item:last-child {
  margin-bottom: 0;
}

.contact-record-item.saved {
  background: #f8fff8;
  border-color: #28a745;
}

.contact-record-item.disabled {
  background: #f8f9fa;
  opacity: 0.7;
}

.record-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
  padding-bottom: 0.5rem;
  border-bottom: 1px solid #e9ecef;
}

.record-number {
  font-weight: 600;
  color: #495057;
  font-size: 1rem;
}

.record-time {
  font-size: 0.8rem;
  color: #6c757d;
}

.form-group {
  margin-bottom: 0;
}

.form-label {
  font-size: 0.9rem;
  font-weight: 600;
  color: #495057;
  margin-bottom: 0.75rem;
  display: block;
}

/* 已保存结果样式 */
.form-value.saved {
  background: #e8f5e8;
  border: 1px solid #28a745;
  border-radius: 8px;
  padding: 1rem;
}

.saved-result {
  display: flex;
  align-items: center;
  gap: 0.75rem;
}

.saved-result i {
  color: #28a745;
  font-size: 1.2rem;
}

.result-text {
  flex: 1;
  font-size: 1rem;
  font-weight: 600;
  color: #155724;
}

.saved-badge {
  background: #28a745;
  color: white;
  font-size: 0.75rem;
  padding: 0.25rem 0.5rem;
  border-radius: 12px;
  font-weight: 600;
}

/* 联系结果选择器样式 */
.contact-result-selector {
  background: white;
  border: 1px solid #dee2e6;
  border-radius: 8px;
  overflow: hidden;
}

/* 下拉菜单和保存按钮容器 */
.result-select-container {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  padding: 0.75rem;
}

/* 下拉菜单样式 */
.contact-result-select {
  flex: 1;
  min-width: 0;
  border: 1px solid #ced4da;
  border-radius: 6px;
  padding: 0.5rem 0.75rem;
  font-size: 0.95rem;
  background-color: white;
  transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
}

.contact-result-select:focus {
  border-color: #80bdff;
  outline: 0;
  box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
}

/* 内联保存按钮样式 */
.save-btn-inline {
  flex-shrink: 0;
  padding: 0.5rem 1rem;
  font-size: 0.875rem;
  border-radius: 6px;
  border: none;
  background-color: #28a745;
  color: white;
  cursor: pointer;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  gap: 0.25rem;
  font-weight: 500;
}

.save-btn-inline:hover:not(:disabled) {
  background-color: #218838;
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.save-btn-inline:active:not(:disabled) {
  transform: translateY(0);
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.save-btn-inline:disabled {
  background-color: #6c757d;
  cursor: not-allowed;
  opacity: 0.6;
}

.save-btn-inline i {
  font-size: 0.875rem;
}

.result-options {
  display: flex;
  flex-direction: column;
}

.result-option {
  padding: 1rem;
  border-bottom: 1px solid #f1f3f4;
  cursor: pointer;
  transition: all 0.2s ease;
  background: white;
}

.result-option:last-child {
  border-bottom: none;
}

.result-option:hover {
  background: #f8f9fa;
}

.result-option.selected {
  background: #e3f2fd;
  border-color: #2196f3;
}

.result-option:active {
  transform: scale(0.98);
}

.option-content {
  display: flex;
  align-items: center;
  gap: 0.75rem;
}

.option-content i {
  font-size: 1.2rem;
  color: #6c757d;
  transition: color 0.2s ease;
}

.result-option.selected .option-content i {
  color: #2196f3;
}

.option-text {
  font-size: 1rem;
  font-weight: 500;
  color: #495057;
  line-height: 1.4;
}

.result-option.selected .option-text {
  color: #1976d2;
  font-weight: 600;
}

/* 禁用状态样式 */
.form-value.disabled {
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  padding: 1rem;
  color: #6c757d;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.form-value.disabled i {
  color: #ffc107;
  font-size: 1.1rem;
}

.form-value.disabled span {
  font-size: 0.95rem;
}

.no-records {
  text-align: center;
  padding: 2rem;
  color: #6c757d;
  font-size: 0.9rem;
}

.no-records i {
  font-size: 2rem;
  margin-bottom: 0.5rem;
  opacity: 0.5;
  display: block;
}

/* 联系信息卡片 */
.contact-info-card {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 1rem;
  margin-bottom: 1rem;
}

/* 患者电话美化样式 */
.patient-phone-section {
  margin-bottom: 1.5rem;
}

.patient-phone-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  padding: 1rem;
  display: flex;
  align-items: center;
  gap: 1rem;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.patient-phone-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, rgba(255,255,255,0.1) 0%, rgba(255,255,255,0.05) 100%);
  pointer-events: none;
}

.patient-phone-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
}

.phone-icon {
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  width: 48px;
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  backdrop-filter: blur(10px);
}

.phone-icon i {
  font-size: 1.5rem;
  color: white;
}

.phone-info {
  flex: 1;
  min-width: 0;
}

.phone-info .phone-label {
  font-size: 0.85rem;
  color: rgba(255, 255, 255, 0.8);
  margin-bottom: 0.25rem;
  font-weight: 500;
}

.phone-info .phone-number {
  font-size: 1.2rem;
  font-weight: 600;
  color: white;
  word-break: break-all;
}

.phone-action-btn {
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: white;
  border-radius: 8px;
  padding: 0.5rem;
  cursor: pointer;
  transition: all 0.2s ease;
  backdrop-filter: blur(10px);
  flex-shrink: 0;
  text-decoration: none;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  /* 确保在所有平台上都能正常触发拨号 */
  -webkit-touch-callout: default;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

.phone-action-btn:hover {
  background: rgba(255, 255, 255, 0.3);
  border-color: rgba(255, 255, 255, 0.5);
  transform: scale(1.05);
  color: white;
  text-decoration: none;
}

.phone-action-btn:active {
  transform: scale(0.95);
  color: white;
  text-decoration: none;
}

.phone-action-btn:focus {
  outline: none;
  color: white;
  text-decoration: none;
}

.phone-action-btn i {
  font-size: 1rem;
}

.phone-section {
  margin-bottom: 1rem;
}

.phone-item {
  margin-bottom: 0.75rem;
}

.phone-item:last-child {
  margin-bottom: 0;
}

.phone-label {
  font-size: 0.8rem;
  color: #6c757d;
  margin-bottom: 0.25rem;
}

.phone-number {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  font-size: 1.1rem;
  font-weight: 600;
}

.phone-item.primary .phone-number {
  color: #007bff;
}

.phone-item.secondary .phone-number {
  color: #28a745;
}

.copy-btn {
  background: none;
  border: 1px solid currentColor;
  color: inherit;
  border-radius: 4px;
  padding: 0.25rem 0.5rem;
  font-size: 0.8rem;
  cursor: pointer;
}

.copy-btn-small {
  background: none;
  border: 1px solid currentColor;
  color: inherit;
  border-radius: 3px;
  padding: 0.15rem 0.3rem;
  font-size: 0.7rem;
  cursor: pointer;
  margin-left: 0.5rem;
  opacity: 0.7;
  transition: opacity 0.2s ease;
  text-decoration: none;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  /* 确保在所有平台上都能正常触发拨号 */
  -webkit-touch-callout: default;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

.copy-btn-small:hover {
  opacity: 1;
  color: inherit;
  text-decoration: none;
}

.copy-btn-small:active {
  transform: scale(0.95);
  color: inherit;
  text-decoration: none;
}

.copy-btn-small:focus {
  outline: none;
  color: inherit;
  text-decoration: none;
}

.basic-info {
  border-top: 1px solid #dee2e6;
  padding-top: 1rem;
}

.info-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 0.5rem;
  font-size: 0.9rem;
}

.info-label {
  color: #6c757d;
  min-width: 80px;
}

.info-value {
  color: #495057;
  text-align: right;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 0.25rem;
}

.info-value.phone {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 0.25rem;
}

.phone-combined-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 0.5rem;
  font-size: 0.9rem;
  flex-wrap: wrap;
  gap: 0.5rem;
}

.phone-group {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  min-width: 0;
  flex: 1;
}

.phone-group .info-label {
  color: #6c757d;
  white-space: nowrap;
  flex-shrink: 0;
}

.phone-group .info-value {
  color: #495057;
  display: flex;
  align-items: center;
  gap: 0.25rem;
  min-width: 0;
}

.info-value.amount {
  color: #28a745;
  font-weight: 600;
}

/* HIS余额 */
.his-balance {
  border-top: 1px solid #dee2e6;
  padding-top: 1rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.balance-label {
  font-size: 0.9rem;
  color: #6c757d;
}

.balance-value .loading {
  color: #6c757d;
  font-size: 0.9rem;
}

.balance-value .error {
  color: #dc3545;
  font-size: 0.9rem;
}

.balance-value .amount {
  font-size: 1.1rem;
  font-weight: 600;
}

.balance-value .amount.positive {
  color: #28a745;
}

.balance-value .amount.zero {
  color: #ffc107;
}

/* 快速指引 */
.quick-guide {
  background: white;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  overflow: hidden;
}

.guide-header {
  padding: 1rem;
  background: #f8f9fa;
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: pointer;
  font-weight: 600;
  color: #495057;
}

.guide-content {
  padding: 1rem;
}

.guide-section {
  margin-bottom: 1rem;
}

.guide-section:last-child {
  margin-bottom: 0;
}

.guide-section h6 {
  font-size: 0.9rem;
  font-weight: 600;
  color: #495057;
  margin-bottom: 0.75rem;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.guide-section h6 i {
  font-size: 1rem;
}

/* 术语样式 */
.terms-list {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.term-item {
  background: #f8f9fa;
  border-radius: 6px;
  padding: 0.75rem;
  border-left: 3px solid #007bff;
}

.term-title {
  font-weight: 600;
  color: #495057;
  margin-bottom: 0.25rem;
  font-size: 0.85rem;
}

.term-content {
  color: #6c757d;
  line-height: 1.4;
  font-size: 0.8rem;
}

/* 话术分类样式 */
.scripts-list {
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
}

.script-category {
  margin-bottom: 0.5rem;
}

.category-title {
  font-weight: 600;
  color: #495057;
  margin-bottom: 0.5rem;
  padding: 0.5rem 0.75rem;
  background: #e9ecef;
  border-radius: 6px;
  border-left: 3px solid #28a745;
  font-size: 0.85rem;
}

.script-items {
  display: flex;
  flex-direction: column;
  gap: 0.375rem;
}

.script-item {
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 6px;
  padding: 0.5rem 0.75rem;
  cursor: pointer;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  gap: 0.5rem;
  font-size: 0.8rem;
}

.script-item:hover {
  background: #e9ecef;
  border-color: #28a745;
  transform: translateY(-1px);
}

.script-item:active {
  transform: translateY(0);
  background: #dee2e6;
}

.script-item i {
  color: #28a745;
  font-size: 0.75rem;
  flex-shrink: 0;
}

/* 注意事项样式 */
.note-list {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.note-item {
  font-size: 0.8rem;
  color: #6c757d;
  display: flex;
  align-items: flex-start;
  gap: 0.5rem;
  line-height: 1.4;
}

.note-item i {
  color: #28a745;
  margin-top: 0.1rem;
  flex-shrink: 0;
  font-size: 0.75rem;
}

/* 详情加载状态 */
.detail-loading {
  text-align: center;
  padding: 2rem;
  color: #6c757d;
}

.detail-empty {
  text-align: center;
  padding: 2rem;
  color: #6c757d;
}

/* 响应式调整 */
@media (max-width: 576px) {
  .mobile-content {
    padding: 0.75rem;
  }
  
  .task-stats {
    gap: 0.5rem;
  }
  
  .detail-stats {
    gap: 0.5rem;
  }
  
  .stat-card {
    padding: 0.75rem;
  }
  
  .stat-number {
    font-size: 1.25rem;
  }
  
  /* 头部导航响应式优化 */
  .modal-header {
    padding: 0.75rem;
    gap: 0.75rem;
  }
  
  .title-navigation-row {
    gap: 0.75rem;
    height: 36px; /* 小屏幕下稍微减小高度 */
  }
  
  .header-left {
    gap: 0.375rem;
  }
  
  .modal-title {
    font-size: 1rem;
    height: 36px; /* 与导航组统一高度 */
  }
  
  .header-navigation {
    padding: 0.2rem 0.4rem;
    gap: 0.2rem;
    height: 36px; /* 与标题统一高度 */
  }
  
  .nav-btn-header {
    min-width: 24px;
    height: 24px;
    padding: 0.2rem 0.4rem;
    font-size: 0.7rem;
  }
  
  .nav-info-header {
    font-size: 0.7rem;
    padding: 0 0.375rem;
  }
  
  .modal-close {
    width: 36px;
    height: 36px;
    font-size: 1.1rem;
  }
}

/* 深色模式支持 */
@media (prefers-color-scheme: dark) {
  .mobile-refund-task {
    background: #121212;
    color: #ffffff;
  }
  
  .task-card, .modal-content, .contact-info-card, .quick-guide {
    background: #1e1e1e;
    border-color: #333;
  }
  
  .stat-item, .stat-card {
    background: #2a2a2a;
  }
  
  .patient-card.uncontacted {
    background: #2a2a1a;
    border-left-color: #ffc107;
  }
}

/* 固定信息区域和可滚动内容样式 */
.contact-record-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  overflow: hidden;
}

.fixed-info-section {
  position: sticky;
  top: 0;
  z-index: 10;
  background: white;
  border-bottom: 2px solid #e9ecef;
  padding: 1rem;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.core-info-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 1rem;
  margin-top: 1rem;
}

.core-info-item {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 0.75rem;
  text-align: center;
  border-left: 4px solid #007bff;
}

.core-info-item.gender {
  border-left-color: #28a745;
}

.core-info-item.id-card {
  border-left-color: #ffc107;
}

.core-info-item.balance {
  border-left-color: #dc3545;
}

.core-info-label {
  font-size: 0.8rem;
  color: #6c757d;
  margin-bottom: 0.25rem;
  font-weight: 500;
}

.core-info-value {
  font-size: 1rem;
  font-weight: 600;
  color: #495057;
}

.core-info-value.amount {
  color: #28a745;
}

.scrollable-content {
  flex: 1;
  overflow-y: auto;
  padding: 1rem;
  background: #f8f9fa;
}

.collapsible-card {
  background: white;
  border-radius: 12px;
  margin-bottom: 1rem;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  overflow: hidden;
  transition: all 0.3s ease;
}

.collapsible-header {
  padding: 1rem;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: pointer;
  border-bottom: 1px solid #dee2e6;
  transition: all 0.2s ease;
}

.collapsible-header:hover {
  background: linear-gradient(135deg, #e9ecef 0%, #dee2e6 100%);
}

.collapsible-header:active {
  transform: scale(0.98);
}

.collapsible-title {
  font-weight: 600;
  color: #495057;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.collapsible-title i {
  color: #007bff;
}

.collapse-icon {
  transition: transform 0.3s ease;
  color: #6c757d;
}

.collapse-icon.expanded {
  transform: rotate(180deg);
}

.collapsible-content {
  max-height: 0;
  overflow: hidden;
  transition: max-height 0.3s ease;
}

.collapsible-content.expanded {
  max-height: 1000px;
}

.collapsible-body {
  padding: 1rem;
}

/* 响应式调整 */
@media (max-width: 576px) {
  .core-info-grid {
    grid-template-columns: 1fr;
    gap: 0.75rem;
  }
  
  .fixed-info-section {
    padding: 0.75rem;
  }
  
  .scrollable-content {
    padding: 0.75rem;
  }
  
  .collapsible-header {
    padding: 0.75rem;
  }
  
  .collapsible-body {
    padding: 0.75rem;
  }
}

/* 新增的核心信息区域样式 */
.core-info-card {
  margin-bottom: 1rem;
}

.core-basic-info {
  margin-bottom: 1rem;
}

.core-basic-info .core-info-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 0.75rem;
  margin-top: 0;
}

.core-basic-info .core-info-item {
  background: #f8f9fa;
  border-radius: 6px;
  padding: 0.5rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-left: 3px solid #007bff;
}

.core-label {
  font-size: 0.8rem;
  color: #6c757d;
  font-weight: 500;
}

.core-value {
  font-size: 0.9rem;
  font-weight: 600;
  color: #495057;
}

.core-his-balance {
  background: linear-gradient(135deg, #e8f5e8 0%, #f0f8f0 100%);
  border-radius: 8px;
  padding: 0.75rem;
  border-left: 4px solid #28a745;
}

.balance-header {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  margin-bottom: 0.5rem;
}

.balance-title {
  font-size: 0.9rem;
  font-weight: 600;
  color: #495057;
}

.balance-content .loading {
  color: #6c757d;
  font-size: 0.9rem;
}

.balance-content .error {
  color: #dc3545;
  font-size: 0.9rem;
}

.balance-content .amount {
  font-size: 1.1rem;
  font-weight: 700;
}

.balance-content .amount.positive {
  color: #28a745;
}

.balance-content .amount.zero {
  color: #ffc107;
}

/* 折叠卡片样式 */
.card-header {
  padding: 1rem;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: pointer;
  border-bottom: 1px solid #dee2e6;
  transition: all 0.2s ease;
}

.card-header:hover {
  background: linear-gradient(135deg, #e9ecef 0%, #dee2e6 100%);
}

.header-content {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  font-weight: 600;
  color: #495057;
}

.header-content i {
  color: #007bff;
}

.card-content {
  padding: 1rem;
}

.detail-info-grid {
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
}

.detail-info-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0.5rem 0;
  border-bottom: 1px solid #f0f0f0;
}

.detail-info-row:last-child {
  border-bottom: none;
}

.detail-label {
  font-size: 0.9rem;
  color: #6c757d;
  font-weight: 500;
  min-width: 80px;
}

.detail-value {
  font-size: 0.9rem;
  color: #495057;
  font-weight: 600;
  text-align: right;
  flex: 1;
}

.detail-value.phone {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  justify-content: flex-end;
}

.detail-value.amount {
  color: #28a745;
}

/* 联系记录表单样式 */
.contact-records-section {
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  overflow: hidden;
}

.section-header {
  padding: 1rem;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border-bottom: 1px solid #dee2e6;
}

.section-header h6 {
  margin: 0;
  font-weight: 600;
  color: #495057;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.header-actions {
  margin-top: 0.75rem;
}

.action-buttons {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 1rem;
}

.navigation-group {
  display: flex;
  align-items: center;
  gap: 0.25rem;
}

.nav-btn {
  width: 28px;
  height: 28px;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

.nav-info {
  font-size: 0.75rem;
  color: #6c757d;
  font-weight: 500;
  min-width: 50px;
  text-align: center;
}

.save-btn {
  white-space: nowrap;
}

/* 单个联系记录保存相关样式 */
.record-save-section {
  margin-top: 1rem;
  padding: 0.5rem;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.record-save-btn {
  width: 100%;
  padding: 0.5rem 1rem;
  font-size: 0.9rem;
  font-weight: 600;
  border-radius: 6px;
  transition: all 0.2s ease;
}

.record-save-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.record-save-btn:not(:disabled):hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(40, 167, 69, 0.3);
}

/* 响应式调整 */
@media (max-width: 576px) {
  .record-save-section {
    padding: 0.4rem;
  }
  
  .record-save-btn {
    font-size: 0.85rem;
    padding: 0.4rem 0.8rem;
  }
  
  .next-record-prompt {
    margin: 0.5rem;
  }
  
  .prompt-actions {
    flex-direction: column;
    gap: 0.5rem;
  }
  
  .prompt-actions .btn {
    width: 100%;
  }
}

/* 跳转下一条记录提示样式 */
.next-record-prompt {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 1050;
  background: white;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
  border: 1px solid #e9ecef;
  animation: promptSlideIn 0.3s ease-out;
  max-width: 90vw;
  width: 320px;
}

@keyframes promptSlideIn {
  from {
    opacity: 0;
    transform: translate(-50%, -50%) scale(0.9);
  }
  to {
    opacity: 1;
    transform: translate(-50%, -50%) scale(1);
  }
}

.prompt-content {
  padding: 1.5rem;
}

.prompt-header {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  margin-bottom: 1rem;
}

.prompt-header i {
  font-size: 1.5rem;
}

.prompt-title {
  font-size: 1.1rem;
  font-weight: 600;
  color: #495057;
}

.prompt-message {
  color: #6c757d;
  margin-bottom: 1.5rem;
  font-size: 0.95rem;
  line-height: 1.4;
}

.prompt-actions {
  display: flex;
  gap: 0.75rem;
  justify-content: center;
}

.prompt-actions .btn {
  padding: 0.5rem 1rem;
  font-size: 0.9rem;
  font-weight: 600;
  border-radius: 6px;
  min-width: 100px;
  transition: all 0.2s ease;
}

.prompt-actions .btn-primary {
  background: linear-gradient(135deg, #007bff, #0056b3);
  border: none;
  box-shadow: 0 2px 8px rgba(0, 123, 255, 0.3);
}

.prompt-actions .btn-primary:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 123, 255, 0.4);
}

.prompt-actions .btn-outline-secondary {
  border-color: #6c757d;
  color: #6c757d;
}

.prompt-actions .btn-outline-secondary:hover {
  background: #6c757d;
  border-color: #6c757d;
  color: white;
}
</style>